
package com.zy.config;

import com.zy.service.PermissionService;
import com.zy.service.StaffService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@Slf4j
public class ShiroConfig {
    @Resource
    private StaffService staffService;
    @Resource
    private PermissionService permissionService;
    @Bean
    public SecurityManager securityManager(){
        DefaultWebSecurityManager securityManager =new DefaultWebSecurityManager();
        securityManager.setRealm(ldcmsRealm());
        securityManager.setCacheManager(ehCacheManager());
        return  securityManager;
    }
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean shiroFilterFactoryBean =new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager());
        Map<String,String> fil =new HashMap<>();
        shiroFilterFactoryBean.setFilterChainDefinitionMap(fil);
        fil.put("/logout1","logout");
        fil.put("/**","authc");
        fil.put("/common","anon");
        fil.put("/css/**","anon");
        fil.put("/webjars/**","anon");
        fil.put("/login","anon");
        shiroFilterFactoryBean.setLoginUrl("/login");

        return shiroFilterFactoryBean;
    }

@Bean
public ldcmsRealm ldcmsRealm(){
        ldcmsRealm ldcmsRealm=new ldcmsRealm();
        ldcmsRealm.setStaffService(staffService);
        ldcmsRealm.setPermissionService(permissionService);
        ldcmsRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return ldcmsRealm;
        }


@Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
    HashedCredentialsMatcher hashedCredentialsMatcher =new HashedCredentialsMatcher();
    hashedCredentialsMatcher.setHashAlgorithmName("md5");
    hashedCredentialsMatcher.setHashIterations(1);
    return hashedCredentialsMatcher;
    }
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(){
        AuthorizationAttributeSourceAdvisor advisor =new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager());
        return advisor;
    }
    @Bean
    public EhCacheManager ehCacheManager(){
        EhCacheManager ehCacheManager =new EhCacheManager();
        ehCacheManager.setCacheManagerConfigFile("classpath:shiro-ehcache.xml");
        return ehCacheManager;
    }
}


